package com.youlu.campus.service.contest;

import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.res.ActivityContestResponse;
import com.youlu.campus.entity.VO.res.ActivityPlusUserQaRes;
import com.youlu.campus.entity.VO.res.CaCertificateResponse;
import com.youlu.campus.entity.VO.res.UserCaHonorRes;
import com.youlu.campus.entity.ca.UserCa;
import com.youlu.campus.entity.domain.CsInfoDomain;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityRewardRuleService;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.ca.CaTemplateService;
import com.youlu.campus.service.ca.UserCaService;
import com.youlu.campus.service.ca.impl.CaCertificateConfigService;
import com.youlu.campus.service.ca.impl.CertificateActivityConfigService;
import com.youlu.campus.service.cache.CacheActivityService;
import com.youlu.campus.service.platform.PointPlatformConfigService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.qa.ActivityQaRuleService;
import com.youlu.campus.service.qa.UserQaInfoService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import com.youlu.campus.service.ranking.entity.UserActivityPointRanking;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class QQMiniContestService {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserQaInfoService userQaInfoService;

    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private CertificateActivityConfigService certificateActivityConfigService;

    @Autowired
    private CaCertificateConfigService caCertificateConfigService;

    @Autowired
    private CaTemplateService caTemplateService;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Autowired
    private ActivityQaRuleService activityQaRuleService;

    @Autowired
    private ActivityRewardRuleService activityRewardRuleService;

    @Autowired
    private UserCaService userCaService;

    @Autowired
    private CacheActivityService cacheActivityService;

    @Autowired
    private PointPlatformConfigService pointPlatformConfigService;


    public CaCertificateResponse receiveCaList(UserPO currentUser, String activityId) {
        List<CertificateActivityConfig> certificateConfigList =
                certificateActivityConfigService.findByActivityId(activityId);
        if (CollectionUtils.isEmpty(certificateConfigList)) {
            throw new BusinessException("证书配置信息未配置");
        }
        ActivityInfo activityInfo = activityService.findOne(activityId);
        HashMap<String, String> caMatchKeyMap = activityInfo.getCaMatchKeyWords();
        if (MapUtils.isEmpty(caMatchKeyMap)) {
            throw new BusinessException("证书领取关键字信息未配置");
        }
        //获取用户参与活动获取到的证书
        List<UserCa> userCaList = userCaService.findByUserIdAndActivityId(currentUser.getId(), activityId);

        //初赛匹配
        String chuSaiKeyWord = caMatchKeyMap.get("c-contest");
        //复赛匹配
        String fuSaiKeyWord = caMatchKeyMap.get("p-contest");
        //决赛匹配
        String jueSaiKeyWord = caMatchKeyMap.get("co-contest");
        //宣传证书
        String inviteKeyWord = caMatchKeyMap.get("invite");
        //初赛证书配置信息
        CertificateActivityConfig chuSaiCertificateConfig = getCertificateConfig(chuSaiKeyWord, certificateConfigList);
        //复赛证书配置信息
        CertificateActivityConfig fuSaiCertificateConfig = getCertificateConfig(fuSaiKeyWord, certificateConfigList);
        //决赛证书配置信息
        CertificateActivityConfig jueSaiCertificateConfig = getCertificateConfig(jueSaiKeyWord, certificateConfigList);
        //宣传证书配置信息
        CertificateActivityConfig inviteCertificateConfig = getCertificateConfig(inviteKeyWord, certificateConfigList);
        //获取答题信息
        List<ActivityQaInfo> activityQaInfoList = activityQaInfoService.findByActivityId(activityId);
        //获取答题规则
        List<ActivityQaRule> qaRuleList = activityQaRuleService.findByActivityId(activityId);
        //初赛答题信息
        ActivityQaInfo chuSaiQaInfo = getQaInfo(1, activityQaInfoList);
        //复赛答题信息
        ActivityQaInfo fuSaiQaInfo = getQaInfo(2, activityQaInfoList);
        //决赛答题信息
        ActivityQaInfo jueSaiQaInfo = getQaInfo(3, activityQaInfoList);
        List<UserCaHonorRes> qaCertificateList = Lists.newArrayList();
        //初赛
        List<UserCaHonorRes> chuSaiCertificateList = buildQaCertificate(1, chuSaiQaInfo, chuSaiCertificateConfig,
                qaRuleList, userCaList);
        if (CollectionUtils.isNotEmpty(chuSaiCertificateList)) {
            qaCertificateList.addAll(chuSaiCertificateList);
        }
        //复赛
        List<UserCaHonorRes> fuSaiCertificateList = buildQaCertificate(1, fuSaiQaInfo, fuSaiCertificateConfig,
                qaRuleList, userCaList);
        if (CollectionUtils.isNotEmpty(fuSaiCertificateList)) {
            qaCertificateList.addAll(fuSaiCertificateList);
        }
        //决赛
        List<UserCaHonorRes> jueSaiCertificateList = buildQaCertificate(1, jueSaiQaInfo, jueSaiCertificateConfig,
                qaRuleList, userCaList);
        if (CollectionUtils.isNotEmpty(jueSaiCertificateList)) {
            qaCertificateList.addAll(jueSaiCertificateList);
        }
        List<UserCaHonorRes> inviteCertificateList = getCertificateList(2, null, inviteCertificateConfig, null, userCaList);
         List<UserCaHonorRes> propagandaCaCertificateList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(inviteCertificateList)) {
            propagandaCaCertificateList.addAll(inviteCertificateList);
        }
        Integer[] index = {1};
        CaCertificateResponse caCertificateResult = new CaCertificateResponse();
        caCertificateResult.setQaCaCertificateList(qaCertificateList.stream().peek(caCertificate ->caCertificate.setSort(index[0]++)).collect(Collectors.toList()));
        caCertificateResult.setPropagandaCaCertificateList(propagandaCaCertificateList.stream().peek(propagandaCaCertificate->propagandaCaCertificate.setSort(index[0]++)).collect(Collectors.toList()));
        activityQaInfoList.clear();
        qaRuleList.clear();
       // qaCertificateList.clear();
        caMatchKeyMap.clear();
        //qaCertificateList.clear();
        return caCertificateResult;
    }

    private List<UserCaHonorRes> buildQaCertificate(Integer type, ActivityQaInfo qaInfo,
                                                    CertificateActivityConfig certificateConfig,
                                                    List<ActivityQaRule> qaRuleList, List<UserCa> userCaList) {
        if (Objects.isNull(qaInfo)) {
            return null;
        }
        return getCertificateList(type, qaInfo, certificateConfig, qaRuleList, userCaList);
    }

    private List<ActivityQaRule> getQaRule(ActivityQaInfo qaInfo, List<ActivityQaRule> qaRuleList) {
        if (CollectionUtils.isEmpty(qaRuleList) || Objects.isNull(qaInfo)) {
            return null;
        }
        return qaRuleList.stream().filter(activityQaRule -> activityQaRule.getActivityQaInfoId().equals(qaInfo.getId())).sorted(Comparator.comparing(ActivityQaRule::getPriority)).collect(Collectors.toList());
    }

    private ActivityQaInfo getQaInfo(Integer qaNumberNo, List<ActivityQaInfo> activityQaInfoList) {
        return activityQaInfoList.stream().filter(activityQaInfo -> activityQaInfo.getNo() == qaNumberNo).findFirst().orElse(null);
    }

    /**
     * 获取证书信息配置信息
     *
     * @param type              1、答题类型 2、宣传员
     * @param certificateConfig 证书配置信息
     * @param qaRuleList        答题规则
     * @param qaInfo            答题标题
     * @param qaRuleList        答题规则
     * @return
     */
    private List<UserCaHonorRes> getCertificateList(Integer type, ActivityQaInfo qaInfo,
                                                    CertificateActivityConfig certificateConfig,
                                                    List<ActivityQaRule> qaRuleList, List<UserCa> userCaList) {
        if (Objects.isNull(certificateConfig)) {
            return null;
        }
        CaActivityLevel[] caActivityLevelArray = certificateConfig.getCaActivityLevel();
        if (ArrayUtils.isEmpty(caActivityLevelArray)) {
            return null;
        }
        final String qaTips = "达到%s分";
        final String inviteTips = "邀请达到%s人";
        List<ActivityRewardRule> activityRewardRuleList = null;
        if (type == 2) {
            activityRewardRuleList = activityRewardRuleService.findByActivityId(certificateConfig.getActivityId());
            if (CollectionUtils.isEmpty(activityRewardRuleList)) {
                throw new BusinessException("未配置邀请匹配规则");
            }
        }
        //获取电子证书配置
        String caType = certificateConfig.getCaType();
        List<CaCertificateConfig> caCertificateConfigList =
                caCertificateConfigService.findByActivityIdAndCaType(certificateConfig.getActivityId(), caType);
        List<ActivityRewardRule> finalActivityRewardRuleList = activityRewardRuleList;
        return Arrays.stream(caActivityLevelArray).map(caActivityLevel -> {
            UserCaHonorRes caCertificate = new UserCaHonorRes();
            caCertificate.setCaType(caType);
            caCertificate.setCaLevel(caActivityLevel.getCaLevel());
            CaCertificateConfig caCertificateConfigGet =
                    caCertificateConfigList.stream().filter(caCertificateConfig -> caCertificateConfig.getCaType().equals(caType) && caCertificateConfig.getCaLevelName().equals(caActivityLevel.getCaLevel())).findFirst().orElse(null);
            if (Objects.nonNull(caCertificateConfigGet)) {
                caCertificate.setCertificateName(caCertificateConfigGet.getCertificateName());
                CaTemplate caTemplate = caTemplateService.detail(caCertificateConfigGet.getTemplateId());
                caCertificate.setBackgroundPic(caTemplate.getBackgroundPic());
            }
            if (CollectionUtils.isNotEmpty(userCaList)) {
                //如果用户存在证书解锁
                long qaCount = userCaList.stream().filter(userCa ->userCa.getCaLevel().equals(caCertificate.getCaLevel()) && userCa.getCaType().equals(caType)).count();
                if (qaCount > 0) {
                    caCertificate.setCaReceivedLock(Boolean.TRUE);
                }
            }
            switch (type) {
                case 1://答题
                    String qaMsg = "暂时未达到达到等级";
                    ActivityQaRule qaRule =
                            qaRuleList.stream().filter(activityQaRule -> activityQaRule.getActivityQaInfoId().equals(activityQaRule.getActivityQaInfoId()) && activityQaRule.getCaName().equals(caCertificate.getCaLevel())).findFirst().orElse(null);
                    if (Objects.nonNull(qaRule)) {
                        switch (qaRule.getInviteOperatorType()) {
                            case "section":
                                qaMsg = qaInfo.getName() + String.format(qaTips, qaRule.getQaStart());
                                break;
                            case "equals":
                                qaMsg = qaInfo.getName() + String.format(qaTips, qaRule.getQaEqu());
                                break;
                            case "rightInterval":
                                qaMsg = qaInfo.getName() + String.format(qaTips, qaRule.getQaEnd());
                                break;
                        }

                    }
                    caCertificate.setQaTips(qaMsg);
                    break;
                case 2://邀请
                    String inviteMsg = "暂时未达到达到等级";
                    ActivityRewardRule inviteRewardRule =
                            finalActivityRewardRuleList.stream().filter(activityRewardRule -> activityRewardRule.getCaName().equals(caCertificate.getCaLevel())).findFirst().orElse(null);
                    if (Objects.nonNull(inviteRewardRule)) {
                        switch (inviteRewardRule.getInviteOperatorType()) {
                            case "section":
                                inviteMsg = String.format(inviteTips, inviteRewardRule.getInviteStart().intValue());
                                break;
                            case "equals":
                                inviteMsg = String.format(inviteTips, inviteRewardRule.getInviteEqu().intValue());
                                break;
                            case "rightInterval":
                                inviteMsg = String.format(inviteTips, inviteRewardRule.getInviteEnd().intValue());
                                break;
                            default:

                        }
                        caCertificate.setInviteTips(inviteMsg);
                    }
                    break;
                default:
            }
            return caCertificate;
        }).collect(Collectors.toList());
    }

    /**
     * 根据证书配置类型获取到相关等级
     *
     * @param caMatchKey
     * @param certificateList
     * @return
     */
    private CertificateActivityConfig getCertificateConfig(String caMatchKey,
                                                           List<CertificateActivityConfig> certificateList) {
        String matchesRegexKey = String.format(".*(%s).*", caMatchKey);
        return certificateList.stream().filter(certificateConfig -> certificateConfig.getCaType().matches(matchesRegexKey)||certificateConfig.getCertificateName().matches(matchesRegexKey)).findFirst().orElse(null);
    }


    /**
     * 活动详情
     *
     * @param activityId
     * @param currentUser
     * @return
     */
    public ActivityContestResponse activityDetail(String appId,UserPO currentUser, String activityId) {
        ActivityInfo activityInfo = activityService.findOne(activityId);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("该活动不存在");
        }
        //获取活动基本信息
        ActivityContestResponse activityContest = new ActivityContestResponse();
        activityContest.setBackGroundImageUrl(activityInfo.getHeaderImageUrl());
        activityContest.setDetail(activityInfo.getDetail());
        activityContest.setRewardsDetail(activityInfo.getRewardsDetail());
        activityContest.setHeaderHeight(activityInfo.getHeaderHeight());
        activityContest.setRewardValueAlias(activityInfo.getRewardValueAlias());
        activityContest.setRewardValueImgUrl(activityInfo.getRewardValueImgUrl());
        activityContest.setInvitePublicistBottomImageUrl(activityInfo.getInvitePublicistBottomImageUrl());
        activityContest.setDetailImage(activityInfo.getDetailImage());
        activityContest.setRewardValueImgUrl(activityInfo.getRewardValueImgUrl());
        List<CsInfoDomain> csInfoList = activityInfo.getCsInfos();
        //获取客服信息
        if (CollectionUtils.isNotEmpty(csInfoList)) {
            Optional<CsInfoDomain> qqOptional =
                    csInfoList.stream().filter(csInfoDomain -> "QQ".equals(csInfoDomain.getType())).findFirst();
            if (qqOptional.isPresent()) {
                if (StringUtils.isNotBlank(qqOptional.get().getNumber())) {
                    activityContest.setQqGroupList(qqOptional.get().getNumber().split(","));
                }
                activityContest.setCsQQGroupImageUrl(qqOptional.get().getImageUrl());
            }
        }
        //QQ客服支持
        activityContest.setCsList(pointPlatformConfigService.findCsByAppIdAndPlatform(appId, "qq"));
        //活动结束时间
        Date endTime = activityInfo.getEndTime();
        activityContest.setStatus(getActivityStatus(endTime));
        //获取答题信息
        ActivityPlusUserQaRes userQaInfo = userQaInfoService.findUserQaInfoByUserIdAndActivityId(currentUser,1, activityId);
        activityContest.setUserQaInfo(userQaInfo);
        if (Objects.nonNull(currentUser)) {
            //获取用户贡献值
            UserActivityPointRanking userActivityPointRanking =
                    userActivityPointRankingService.findByUserIdAndActivityId(currentUser.getId(), activityId);
            if (Objects.nonNull(userActivityPointRanking)) {
                activityContest.setRewardValue(userActivityPointRanking.getQuantity().intValue());
                activityContest.setNickName(currentUser.getNickName());
                activityContest.setAvatarUrl(currentUser.getAvatarUrl());
            }
            //获取用户报名
            UserInfoExtend userInfoExtend = userInfoExtendService.findByUserIdAndAppId(currentUser);
            if (Objects.nonNull(userInfoExtend)) {
                activityContest.setJoined(Boolean.TRUE);
            }
            UserParticipateActivityInfo userParticipateActivityInfo =
                    userParticipateActivityInfoService.findByUserIdActivityId(currentUser.getId(), activityId);
            if (Objects.nonNull(userParticipateActivityInfo)) {
                activityContest.setJoinActivity(Boolean.TRUE);
            }
        }
        //获取任务信息
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if (Objects.nonNull(activityTaskInfo)) {
            activityContest.setInviteValue(activityTaskInfo.getRatio().intValue());
            activityContest.setShareInviteButtonType(activityTaskInfo.getShareInviteButtonType());
            activityContest.setTaskId(activityTaskInfo.getId());
            activityContest.setInviteButtonTips(activityTaskInfo.getInviteButtonTips());
            activityContest.setShareInviteButtonBackGroundImgUrl(activityTaskInfo.getShareInviteButtonBackGroundImgUrl());
        }
        //获取证书限制进度提示文案
        CertificateReceiveLimit certificateReceiveLimit = activityInfo.getCertificateReceiveLimit();
        if (Objects.nonNull(certificateReceiveLimit)) {
            Integer rewardValue = activityContest.getRewardValue();
            certificateReceiveLimit.setCertificateRate(rewardValue);
            activityContest.setCertificateReceiveLimit(certificateReceiveLimit);
        }
        return activityContest;
    }

    public String getActivityType(String activityId){
        ActivityInfo activityInfo = cacheActivityService.findById(activityId);
        return activityInfo.getType();
    }

    public Integer getActivityStatus(Date endTime) {
        if (Objects.isNull(endTime)) {
            //活动未开始
            return 1;
        }
        Date now = new Date();
        return endTime.after(now) == true ? 2 : endTime.before(now) == true ? 3 : 1;
    }


}
